package cn.xuqiudong.sso.server.session.impl;

import cn.xuqiudong.sso.common.model.RefreshTokenContent;
import cn.xuqiudong.sso.server.config.SsoConfiguration;
import cn.xuqiudong.sso.server.session.RefreshTokenManager;
import cn.xuqiudong.sso.server.storage.StorageStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 *  刷新凭证管理
 *
 * @author Joe
 */
@Component
public class RefreshTokenManagerImpl implements RefreshTokenManager {

    private Logger logger = LoggerFactory.getLogger(RefreshTokenManagerImpl.class);

    @Resource
    private StorageStrategy<RefreshTokenContent> storageStrategy;

    @Resource
    private SsoConfiguration ssoConfiguration;


    @Override
    public int expire() {
        return ssoConfiguration.getTimeout();
    }

    @Override
    public String cacheName() {
        return "refresh-token";
    }

    @Override
    public void storage(String refreshToken, RefreshTokenContent refreshTokenContent) {
        storageStrategy.storage(cacheName(), refreshToken, refreshTokenContent, expire());
    }

    @Override
    public RefreshTokenContent validate(String refreshToken) {
        RefreshTokenContent refreshTokenContent = storageStrategy.remove(cacheName(), refreshToken, RefreshTokenContent.class);
        if (refreshTokenContent == null) {
            refreshTokenContent = getTemporaryStorageRefreshToken(refreshToken);
        }
        return refreshTokenContent;
    }

    /**
     * 暂存refreshToken 和新的 accessToken 的关联关系
     * @param refreshToken refreshToken
     * @param refreshTokenContent refreshTokenContent 其中包含了新的accessToken
     */
    @Override
    public void temporaryStorageRefreshToken(String refreshToken, RefreshTokenContent refreshTokenContent) {
        storageStrategy.storage(temporaryStorageCacheName(), refreshToken, refreshTokenContent, 60);
    }

    @Override
    public RefreshTokenContent getTemporaryStorageRefreshToken(String refreshToken) {
        return storageStrategy.getData(temporaryStorageCacheName(), refreshToken, RefreshTokenContent.class);
    }

    /**
     * 暂存的refreshToken 的cacheName
     * @return cache name
     */
    private String temporaryStorageCacheName() {
        return "temporary-" + cacheName();
    }

}
